package org.ykh.service.mybatis.factory;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.SoftReferenceObjectPool;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Mybatis对象工厂
 * @author ykh
 */
@Slf4j
public class PooledObjectFactory extends DefaultObjectFactory {


    private static class EasyPooledFactoryFactory<T> extends BasePooledObjectFactory<T> {
        private final Class<T> type;


        public EasyPooledFactoryFactory(Class<T> type) {
            this.type = type;
        }

        @Override
        public T create() throws Exception {
            Constructor<T> constructor = type.getConstructor();
            return constructor.newInstance();
        }

        @Override
        public PooledObject<T> wrap(T obj) {
            return new DefaultPooledObject<T>(obj);
        }
    }

    //线程安全问题
    private static final ConcurrentHashMap<Class<?>, ObjectPool<?>> poolMap = new ConcurrentHashMap<>();


    public static <T> void returnObject(List<T> objList, Class<T> type) throws Exception {
        if (objList == null) throw new RuntimeException("objList cannot be null");
        final ObjectPool<T> objectPool = (ObjectPool<T>) poolMap.get(type);
        if (objectPool == null) {
            log.warn("异常操作,类型{}应该获取到pool",type);
            return;
        }
        for (T t : objList) {
            objectPool.returnObject(t);
        }
    }

    public static <T> void clean(List<T> objList, Class<T> type) {
        final ObjectPool<T> objectPool = (ObjectPool<T>) poolMap.get(type);
        if (objectPool == null) {
            log.warn("异常操作,类型{}应该获取到pool",type);
            return;
        }
        try {
            for (T t : objList) {
                objectPool.invalidateObject(t);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    public <T> T newObj(Class<T> type) {

        if (type == List.class || type == Collection.class || type == Iterable.class) {
            return super.create(type,null,null);
        } else if (type == Map.class) {
            return super.create(type,null,null);
        } else if (type == SortedSet.class) {
            return super.create(type,null,null);
        } else if (type == Set.class) {
            return super.create(type,null,null);
        }

        ObjectPool<T> objectPool = (ObjectPool<T>) poolMap.computeIfAbsent(type,
                k -> new SoftReferenceObjectPool<>(new EasyPooledFactoryFactory<>(type)));

        try {
            return objectPool.borrowObject();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    @Override
    public <T> T create(Class<T> type) {
        return newObj(type);
    }


    @Override
    public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
        if (constructorArgTypes == null || constructorArgs == null) {
            return create(type);
        }
        if (constructorArgTypes.size() != constructorArgs.size()) {
            throw new RuntimeException("Illegal parameter. Force the size of constructorArgType and constructorArgs " +
                    "to be equal");
        }
        final T t = newObj(type);
        final Class<?>[] parameterTypes = constructorArgTypes.toArray(new Class<?>[]{});
        try {
            final Constructor<T> constructor = type.getConstructor(parameterTypes);
            final Parameter[] parameters = constructor.getParameters();
            for (int i = 0; i < parameters.length; i++) {
                Parameter parameter = parameters[i];
                final Field field = type.getField(parameter.getName());
                field.setAccessible(true);
                field.set(t, constructorArgs.get(i));
            }
        } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return t;
    }
}
